module(..., package.seeall)

function make_graph(l) 
   local g = {} 
   g.length = l 
   for i = 1,l do g[i] = {} end 
   return g 
end 

function extend_graph(g,new_amt) 
   local old_l = g.length 
   g.length = old_l + new_amt 
   for i = old_l+1, g.length do 
      g[i]={} 
   end 
   return g 
end 

function start_naming(g) 
   g.name_to_node = {} 
   g.node_to_name = {} 
end

function node_of_name(g,name) 
   return g.name_to_node[name]
end 

function name_of_node(g,i) 
   if g.node_to_name
   then 
      return g.node_to_name[i]
   else if i
      then 
	 return string.format("%d", i)
      else 
	 return "None"
      end 
   end 
end

function give_node_name(g,i,name) 
   g.name_to_node[name] = i 
   g.node_to_name[i] = name  
end 


function set_adj(g,n,edges) 
   if 1<=n<=g.length 
   then 
      g[n]=edges 
   else 
      error(string.format("Node %d out of bounds for graph of length %d", 
			  n, g.length), 1)
   end
end

function adj(g,n)  
   if 1<=n<=g.length 
   then 
      return g[n] 
   else 
      error(string.format("Node %d out of bounds for graph of length %d", 
			  n, g.length), 1)
   end
end
   
   
function print_graph(g,file)
   file = file or io.stdout 
   file:write("\n{\n")
   for i = 1,g.length do 
      if g[i] 
      then    
	 file:write(string.format("  [%d] = {", i))
	 for _,e in ipairs(g[i]) do 
	    file:write(string.format(" {dst = %d},", e.dst))
	 end 
	 file:write(" },\n")
      else 
	 file:write("  {},\n")
      end 
   end 
   file:write(string.format("  length = %d\n}\n", g.length))
end 
